<template>
  <div class="countup">
    <span ref="spanRef" />
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, defineProps, nextTick } from 'vue'
import { CountUp, CountUpOptions } from 'countup.js'

const props = defineProps<{
  options?: any
  number: number
}>()

const options: CountUpOptions = {
  decimalPlaces: 2, // 保留两位
  duration: 2, // 动画时长
  separator: ',', // 千位分割
  decimal: '.', // 小数分割
  prefix: '￥' // 单位
}

const spanRef = ref<HTMLElement>()
onMounted(() => {
  if (spanRef.value) {
    const ops = Object.assign(options, props.options)
    let demo = new CountUp(spanRef.value!, props.number, ops)
    if (!demo.error) {
      demo.start()
    } else {
      console.error(demo.error)
    }
  } else {
    nextTick(() => {
      const ops = Object.assign(options, props.options)
      let demo = new CountUp(spanRef.value!, props.number, ops)
      if (!demo.error) {
        demo.start()
      } else {
        console.error(demo.error)
      }
    })
  }
})
</script>

<style scoped></style>
